package com.ddx.service.impl;


import com.ddx.common.enums.Platform;
import com.ddx.common.redis.RedisService;
import com.ddx.common.util.MD5;
import com.ddx.service.IUserTokenService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 用户TOKEN服务的REDIS实现
 *
 * @author Zhao Longhua
 * @date 2017年8月31日下午1:50:05
 */
@Service("iUserTokenService")
public class UserTokenServiceImpl implements IUserTokenService {
	private static Logger log = LoggerFactory.getLogger(RedisService.class);
	@Autowired
	private RedisService redisService;

	// 30天
	private static final Long DEFAULT_TIME_OUT = 60L * 60 * 24 * 30;

	@Override
	public String createToken(String mobile, String salt, Platform platform) throws Exception {
		String redisToken = MD5.EncoderByMd5(mobile + salt);
        String redisKey = platform.getKey() + ":" + mobile;
		redisService.set(redisKey, redisToken, DEFAULT_TIME_OUT);
        return redisToken;
	}

	@Override
	public String getToken(String mobile, Platform platform) throws Exception {
		String redisKey = platform.getKey() + ":" + mobile;
        String token = redisService.get(redisKey)==null?"":redisService.get(redisKey).toString();
        return token;
	}

	@Override
	public void expireToken(String mobile, Platform platform, Long seconds) throws Exception {
		String redisKey = platform.getKey() + ":" + mobile;
		redisService.expire(redisKey, seconds);
	}

	@Override
	public void deleteToken(String mobile, Platform platform) {
		String redisKey = platform.getKey() + ":" + mobile;
        try {
             redisService.remove(redisKey);
        } catch (Exception e) {
			log.error("删除redis失败{}",redisKey);
        }
	}

}
